﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xrm.Sdk;

namespace XrmLibrary.Extensions
{
    public static class EnumerableExtensions
    {
        /// <summary>
        /// Formats an IEnumerable collection of items as a comma separated String.
        /// </summary>
        /// <param name="enumerable">The list.</param>
        /// <param name="delimiter">The delimiter.</param>
        /// <returns>Formatted comma separated String representation of the items.</returns>
        public static String FormatAsCsv(this IEnumerable enumerable, String delimiter = ",")
        {
            StringBuilder sb = new StringBuilder();
            foreach(var item in enumerable)
            {
                sb.AppendFormat("{0}{1}", item, delimiter);
            }
            sb.Remove(sb.Length - 1, 1);
            return sb.ToString();
        }

        /// <summary>
        /// Gets an enumerable collection of a specific attribute with type T from an enumerable collection of entities.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="entities">The entities.</param>
        /// <param name="attributeLogicalName">Name of the attribute logical.</param>
        /// <returns>Enumerable collection of specific attribute.</returns>
        public static IEnumerable<T> GetAttributeValues<T>(this IEnumerable<Entity> entities, String attributeLogicalName)
        {
            foreach(Entity entity in entities)
            {
                yield return entity.GetAttributeValue<T>(attributeLogicalName);
            }
        }

    }
}
